import shutil
import re
import os
from django.contrib import messages
from file_manage import models
from Method_Decorate import Decoration
from Automated_Testing import settings

import email
from django.core import mail
import hashlib
#request.session有相关的值！context_fun['t_yaml_file_path']
session_type={'Total':'t_yaml_file_path'}  #session位置
directory_name_type={'Total':'Total_case','report':"Report"}
def up_load_to_file_manage(user_id,file_path,type='Total'):
    """
    负责将生成的用例上传到file_manage对应的管理之中
    :param file_path:上传文件的路径
    :param type: 生成的是小用例还是总用例？目前只做总用例的
    user_id:用户名
    :return:
    """
    # gen_path=request.session['msg'][session_type[type]]               #生成xx文件的位置
    user_database=models.User.objects.get(name=user_id)   #目前登录用户为？
    parent_directory_database = models.Directory.objects.filter(name="/", path="", owner=user_database)  #用户默认文件夹"/"
    if not models.Directory.objects.filter(name=directory_name_type[type],owner=user_database):  #如果不存在total文件夹则新建一个
        models.Directory.objects.create(
            name=directory_name_type[type],      #Total_case
            owner=user_database,
            parent=parent_directory_database[0],
            path=directory_name_type[type],
        )
    directory_database=models.Directory.objects.get(name=directory_name_type[type],owner=user_database)
    sha1_value=CalcSha1(file_path)
    if models.File.objects.filter(path=directory_name_type[type],digest=sha1_value,owner=user_database):
        #数据库存在相同文件的时候
        return models.File.objects.filter(path=directory_name_type[type],digest=sha1_value,owner=user_database)[0]
    file_name=os.path.basename(file_path)
    file_to_path=os.path.join(models.get_media_abspath(),sha1_value)
    if not os.path.exists(file_to_path):
        #当不存在相同文件夹时  将文件复制到这
        os.mkdir(file_to_path)
        shutil.copy(file_path,file_to_path)
    #更新file
    file_database=models.File.objects.create(
        name=re.sub(r'[%/]', '_', file_name),  # 给用户看的名字，去掉正斜杠和百分号，just in case
        owner=user_database,
        parent=directory_database,
        digest=sha1_value,  # 服务器上真正的名字 sha1值
        path=directory_database.path,  # 用户路径，用户给用户展示，不包含文件名
        size=os.path.getsize(file_path),  # 文件大小
    )
    #更新link
    models.Link.add_one(file_database)
    return  file_database







def CalcSha1(filepath):
    """
    返回文件的sha1的值
    :param filepath:
    :return:
    """
    with open(filepath,'rb') as f:
        digest = hashlib.sha1()
        digest.update(f.read())
        hash = digest.hexdigest()
        return hash


# @Decoration.check_login
def send_emial_appendix(user_name,file_path,File=None,fail_num=0):
    """
    附带附件发送邮件的方法
    :param file_path:  文件路径
    :param receive_email: 一个用户邮箱的list
    :param user_name:当前用户
            File:跑的总用例的models
    :return:
    """

    user_database=models.User.objects.get(name=user_name)
    receive_email=[]
    if user_database.email_condition==False:
        return
    elif user_database.email_condition==True:
        if (File == None):
            receive_email=user_database.email_data.all()  #queryset对象
        else:#File不为空，也就是在数据库中File有备份
            receive_email=File.email_data.all()
        if not receive_email.exists():
            return
        receive_email=list(receive_email)
        receive_email=[str(tmp) for tmp in receive_email]
        receive_email.append("zmvision_auto@163.com")
    # if not isinstance(receive_email,Quesery):
    #     receive_email=[receive_email]
    if fail_num<0:
        subject= "{0}的测试没有成功完成".format(user_name)
    elif fail_num==0:
        subject = "{0}的测试已经完成，本次测试没有错误".format(user_name, fail_num)
    else:
        subject= "{0}的测试已经完成，本次测试失败数量为{1}".format(user_name,fail_num)
    # subject= "{0}的测试已经完成，测试失败数量为{1}".format(user_name,fail_num)
    body="测试报告在邮件附录里，请查看"
    html_content="<p>测试报告在邮件附录里，请查看。</p>" \
                 "<p>此邮箱为专用发送邮箱。</p>" \
                 "<p>请不要<strong>回传邮件</strong>。</p>"
    from_email=settings.DEFAULT_FROM_EMAIL
    msg=mail.EmailMultiAlternatives(subject,body,from_email,receive_email)
    msg.attach_alternative(html_content, "text/html")
    #添加附件
    with open(file_path,'rb') as f:
        appendix=f.read()
        file_name=os.path.basename(file_path)
        tmp=email.header.make_header([(file_name, 'utf-8')]).encode('UTF-8')
        msg.attach(tmp,appendix)
    try:
        if msg.send():
            print("邮件发送成功！")
        else:
            print("邮件发送失败！")
    except Exception as e:
        print(e)

# apperror邮件发送
def send_emial_app_error(user_name,file_path,File=None):
    """
    附带附件发送邮件的方法
    :param file_path:  文件路径
    :param receive_email: 一个用户邮箱的list
    :param user_name:当前用户
            File:跑的总用例的models
    :return:
    """

    user_database=models.User.objects.get(name=user_name)
    receive_email=[]
    if user_database.email_condition==False:
        return
    elif user_database.email_condition==True:
        if (File == None):
            receive_email=user_database.email_data.all()  #queryset对象
        else:#File不为空，也就是在数据库中File有备份
            receive_email=File.email_data.all()
        if not receive_email.exists():
            return
        receive_email=list(receive_email)
        receive_email=[str(tmp) for tmp in receive_email]
        receive_email.append("zmvision_auto@163.com")
    # if not isinstance(receive_email,Quesery):
    #     receive_email=[receive_email]
    subject= "你好，{0}的测试已经完成".format(user_name)
    body="测试报告在邮件附录里，请查看"
    html_content="<p>测试报告在邮件附录里，请查看。</p>" \
                 "<p>此邮箱为专用发送邮箱。</p>" \
                 "<p>请不要<strong>回传邮件</strong>。</p>"
    from_email=settings.DEFAULT_FROM_EMAIL
    msg=mail.EmailMultiAlternatives(subject,body,from_email,receive_email)
    msg.attach_alternative(html_content, "text/html")
    #添加附件
    with open(file_path,'rb') as f:
        appendix=f.read()
        file_name=os.path.basename(file_path)
        tmp=email.header.make_header([(file_name, 'utf-8')]).encode('UTF-8')
        msg.attach(tmp,appendix)
    try:
        if msg.send():
            print("邮件发送成功！")
        else:
            print("邮件发送失败！")
    except Exception as e:
        print(e)


# send_emial_appendix("wwm","C:\\Users\\Versirity\\Desktop\\command_20190511_wa.txt","847700914@qq,com")
# def total_run_to_case(request,)